package com.example.shiro.filter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.apache.shiro.web.util.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.example.shiro.entity.UserInfo;

public class LoginFormAuthenticationFilter extends FormAuthenticationFilter {

    private static Logger logger = LoggerFactory.getLogger(LoginFormAuthenticationFilter.class);
    
    @Override
    protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request,
            ServletResponse response) throws Exception {
        
        UserInfo user = (UserInfo)SecurityUtils.getSubject().getPrincipal();
        
        if(user != null) {
            HttpServletRequest req = (HttpServletRequest) request;
            String clientType = (String) req.getParameter("clienttype");
            logger.debug("[LOGIN]login success(user:" + user.getName() + ", client:" + clientType + ")");
            if("pc".equals(clientType)) { // 请求方为pc，执行原方法
                return super.onLoginSuccess(token, subject, request, response);
            } else { // 其他，根据类型跳转指定页面
                WebUtils.getAndClearSavedRequest(request); // 清除登录前请求路径
                String fallbackUrl = null;
                fallbackUrl = "/static/" + clientType + ".jsp"; // 自定义跳转界面
                WebUtils.redirectToSavedRequest(request, response, fallbackUrl);
            }
        }
        return false;
    }
}